#include "modem.h"
#include "userio.h"
#include "gpg.h"

/**
 * userio()
 * Responsible for accepting and transmitting user input.
 */
void * userio(void* fdptr)
{
	int fd = *(int*)fdptr;
	//printf("Thread Started\n");
	int mode=0;
	char buffer[128];
	char encrypted_buffer[GPG_BUFFER_LENGTH];
	char buffer2[GPG_BUFFER_LENGTH + 10];
	while(mode != -100)
	{
		memset(buffer, 0, 128);
		memset(buffer2, 0 ,GPG_BUFFER_LENGTH+10);
		int offset = 0;
		fgets(buffer,128,stdin);
		//printf("Read %s\n", buffer);
		char header[7];
		if (buffer[0] == '/')
		{
			if (strncmp(buffer, "/quit", strlen("/quit")) == 0)
			{
				disconnect(fd);
				exit(0);
			}
			else if (strncmp(buffer, "/nick", strlen("/nick")) == 0)
			{
				strcpy(header,"NICK");
				offset = 5;
			}

		}
		else
		{
			strcpy(header,"MSG ");
			printf("Encrypting.\n");
			//recipient = identity;
			encrypt_gpg(buffer, encrypted_buffer);
		//	strcpy(encrypted_buffer, buffer);
			printf("Message encrypted.\n");
		}
		strncat(buffer2,header,strlen(header));
		strncat(buffer2,encrypted_buffer+offset,strlen(encrypted_buffer));
//		strncat(buffer,"\r",1);
		buffer2[strlen(buffer2)-1] = '\r';
		//printf("Sending %s\n", buffer2);
		send_device(fd,buffer2);
		
	} 
	return fdptr;
}

